from django.conf import settings
import requests, urllib, json
import logging

logger = logging.getLogger(__name__)


class requests_SDK(requests.Session):
    """凡商通讯请求"""

    if settings.DEBUG:
        host = "https://mini-api-t.fs028.com"  # 测试
        code = "mstVMxzPwDYvJxPEpUVj"
    else:
        host = "https://mini-api.fs028.com"  # 正式
        code = "XeszksJSamygcKmPoJgp"
    status = 1

    def has_headers(self):
        return self.headers

    def do_get(self, url="", headers=None, params=None, data=None, verify=False):
        if not self.status:
            return None
        url = self.host + url
        try:
            r = self.get(url, headers=headers, params=params, data=data, verify=verify)
            x = r.json()
        except BaseException as err:
            logger.warn(f"[Fsyg] [GET] [{url}] {err} {r.text}")
            return None
        else:
            if not x.get("code") == 0:
                logger.warn(f"[Fsyg] [GET] [{url}] [{x}]")
                return None
            return x

    def do_post(
        self, url="", headers=None, params=None, data=None, json=None, verify=False
    ):
        if not self.status:
            return None
        url = self.host + url
        try:
            r = self.post(
                url, headers=headers, params=params, data=data, json=json, verify=verify
            )
            x = r.json()
        except BaseException as err:
            logger.warn(f"[Fsyg] [GET] [{url}] {err} {r.text}")
            return None
        else:
            if not x.get("code") == 0:
                logger.warn(f"[Fsyg] [GET] [{url}] [{x}]")
                return None
            return x
